package com.xhh.nphm.web.controller.system;

import com.alibaba.fastjson.JSONObject;
import com.xhh.nphm.common.core.controller.BaseController;
import com.xhh.nphm.common.core.domain.AjaxResult;
import com.xhh.nphm.common.core.domain.entity.SysUser;
import com.xhh.nphm.common.core.page.TableDataInfo;
import com.xhh.nphm.common.utils.StringUtils;
import com.xhh.nphm.system.domain.MakeTag;
import com.xhh.nphm.system.domain.MakeTagUser;
import com.xhh.nphm.system.domain.TagLibrary;
import com.xhh.nphm.system.service.ITagService;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 标签库
 */
@RestController
@RequestMapping("/system/tag")
public class TagController extends BaseController {

    private final String prefix = "system/tag";

    @Resource
    private ITagService tagService;

    /**
     * 打开标签管理页面
     * @return
     */
    @GetMapping("/tagList")
    public ModelAndView tagList(){
        return new ModelAndView(prefix+"/tagList");
    }

    /**
     * 加载列表数据
     * @param tagLibrary 标签库实体
     * @return
     */
    @PostMapping("/tagListJson")
    public TableDataInfo tagListJson(TagLibrary tagLibrary){
        startPage();
        List<TagLibrary> tagList =  tagService.selectTagListJson(tagLibrary);
        return getDataTable(tagList);
    }

    /**
     * 获取数据集合
     */
    @GetMapping("/autoComplete")
    @ResponseBody
    public AjaxResult autoComplete() {
        AjaxResult ajax = new AjaxResult();
        List<String> tags = tagService.autoComplete();
        String[] arrays = null;
        Integer size = tags.size();
        if(tags != null && size > 0){
            arrays = tags.toArray(new String[size]);
        }
        ajax.put("value",arrays);
        return ajax;
    }

    /**
     * 打开新增标签页面
     * @return
     */
    @GetMapping("/addTag")
    public ModelAndView addTag(){
        return new ModelAndView(prefix+"/addTag");
    }

    /**
     * 保存新增数据
     * @param tagLibrary 标签实体
     * @return
     */
    @PostMapping("/addTag")
    public AjaxResult saveAddTag(TagLibrary tagLibrary){
        AjaxResult ajax = AjaxResult.success();
        tagLibrary.setCreateTime(new Date());//添加时间
        tagLibrary.setUpdateTime(new Date());//修改时间
        tagLibrary.setIsDel(0);
        if(tagService.saveTag(tagLibrary)){
            return ajax;
        }
        return error("新增失败，请重试");
    }

    /**
     * 打开编辑标签页面
     * @param tagNo 编号
     * @return
     */
    @GetMapping("/editTag/{tagNo}")
    public ModelAndView editTag(ModelMap map, @PathVariable("tagNo") Long tagNo){
        TagLibrary tagLibrary = tagService.selectTagByTagNo(tagNo);
        if(tagLibrary != null){
            map.put("tag",tagLibrary);
        }
        return new ModelAndView(prefix+"/editTag");
    }

    /**
     *
     * @param tagLibrary
     * @return
     */
    @PostMapping("/editTag")
    public AjaxResult savedEditTag(TagLibrary tagLibrary){
        tagLibrary.setUpdateTime(new Date());
        if (tagService.updateTag(tagLibrary)) {
            return success();
        }
        return error("修改失败，请重试");
    }

    @PostMapping("/removeTag/{tagNo}")
    public AjaxResult removeTag(@PathVariable("tagNo") Long tagNo){
        if (tagService.removeTag(tagNo)) {
            return success();
        }
        return error("删除失败，请重试");
    }

    /**
     * 打开电话工单打标签页面
     * telId 电话初稿 id
     * @return
     */
    @GetMapping("/addTelWFTag")
    public ModelAndView addTelWFTag(ModelMap map,String telId){
        SysUser user = getSysUser();
        // 查询工单已有标签
        List<Map<String, Object>> telExistTags = tagService.selectTelExistTag(telId,user.getDeptId().toString(),user.getUserId().toString());
        if(telExistTags != null && telExistTags.size() > 0){
            map.put("wfTag",telExistTags);
        }
        // 查询常用标签
        List<Map<String, Object>> commonTag = tagService.selectCommonTag();
        if(commonTag != null && commonTag.size() >0){
            map.put("commonTag",commonTag);
        }
        map.put("recordId",telId);
        map.put("type",1);//电话1 信件2
        return new ModelAndView(prefix+"/makeTag");
    }

    /**
     * 打开信件工单打标签页面
     * mailId 信件初稿 id
     * @return
     */
    @GetMapping("/addMailWFTag")
    public ModelAndView addMailWFTag(ModelMap map,String mailId){
        SysUser user = getSysUser();
        // 查询常用标签
        List<Map<String, Object>> commonTag = tagService.selectCommonTag();
        if(commonTag != null && commonTag.size() >0){
            map.put("commonTag",commonTag);
        }
        // 查询工单已有标签
        List<Map<String, Object>> mailExistTags = tagService.selectMailExistTag(mailId,user.getDeptId().toString(),user.getUserId().toString());
        if(mailExistTags != null && mailExistTags.size() > 0){
            map.put("wfTag",mailExistTags);
        }
        map.put("recordId",mailId);
        map.put("type",2);//电话1 信件2
        return new ModelAndView(prefix+"/makeTag");
    }

    @GetMapping("/selectByTagName")
    @ResponseBody
    public AjaxResult selectByTagName(String tagName){
        Long tagNo = tagService.selectTagByTagName(tagName);
        if(tagNo != null && tagNo > 0){
            return AjaxResult.success("查询成功",tagNo);
        }
        return error();
    }

    /**
     * 保存对应工单打标信息
     * @return
     */
    @PostMapping("/saveWFTag")
    public AjaxResult saveWFTag(MakeTag makeTag, String tags){
        boolean flag = false;
        if(StringUtils.isNotNull(tags)){
            List<Map<String, Object>> tagsList = JSONObject.parseObject(tags, List.class);
            if(tagsList != null) {
                for (Map<String, Object> map : tagsList) {
                    String tagNo = (String) map.get("tagNo");
                    String tagName = (String) map.get("tagName");
                    long tagPkid = 0;
                    if (tagNo.equals("-1")) {
                        Long tagId = tagService.selectTagByTagName(tagName);
                        if (tagId == null) {
                            //添加标签到标签库
                            TagLibrary tagLibrary = new TagLibrary();
                            tagLibrary.setTagName(tagName);
                            tagLibrary.setCreateTime(new Date());
                            tagLibrary.setUpdateTime(new Date());
                            tagLibrary.setIsDel(0);
                            tagLibrary.setIsCommon(0);
                            tagService.saveTag(tagLibrary);
                        }else{
                            tagPkid = tagId;
                        }
                    }
                    Long pkid = Long.parseLong(tagNo) == -1 ? (tagPkid == 0 ? tagService.selectTagByTagName(tagName) : tagPkid) : Long.parseLong(tagNo);
                    //记录添加信息
                    makeTagByUserInfo(pkid,tagName,makeTag);
                    //给工单添加标签
                    makeTag.setTagPkid(pkid);
                    makeTag.setTagName(tagName);
                    if (makeTag.getType() == 1) {//电话
                        flag = tagService.saveTelMakeTag(makeTag);
                    } else if (makeTag.getType() == 2) {//信件
                        flag = tagService.saveMailMakeTag(makeTag);
                    }
                }
            }
            if(flag){
                return success();
            }
        }
        return error("添加失败，请重试");
    }

    /**
     * 删除工单的标签
     * @param makeTag
     * @return
     */
    @PostMapping("/deleteWFTag")
    public AjaxResult deleteWFTag(MakeTag makeTag){
        SysUser user = getSysUser();
        if (tagService.deleteWFTag(makeTag,user.getDeptId().toString())) {
            return success();
        }
        return error("删除失败，请重试");
    }

    /**
     * 查询已存在的电话标签
     * @return
     */
    @GetMapping("/telTagRefresh")
    @ResponseBody
    public AjaxResult telTagRefresh(String telId){
        SysUser user = getSysUser();
        List<Map<String, Object>> telExistTag = tagService.selectTelExistTag(telId, user.getDeptId().toString(), user.getUserNo());
        if(telExistTag != null && telExistTag.size() > 0){
            return AjaxResult.success("查询成功",telExistTag);
        }
        return error();
    }

    /**
     * 查询已存在的信件标签
     * @return
     */
    @GetMapping("/mailTagRefresh")
    @ResponseBody
    public AjaxResult mailTagRefresh(String mailId){
        SysUser user = getSysUser();
        List<Map<String, Object>> mailExistTag = tagService.selectMailExistTag(mailId, user.getDeptId().toString(), user.getUserNo());
        if(mailExistTag != null && mailExistTag.size() > 0){
            return AjaxResult.success("查询成功",mailExistTag);
        }
        return error();
    }

    public void makeTagByUserInfo(Long tagNo,String tagName,MakeTag makeTag){
        SysUser sysUser = getSysUser();
        MakeTagUser makeTagUser = new MakeTagUser();
        makeTagUser.setTagPkid(tagNo);
        makeTagUser.setTagName(tagName);
        makeTagUser.setDeptId(sysUser.getDeptId().toString());
        makeTagUser.setDeptName(sysUser.getDeptName());
        makeTagUser.setUserId(sysUser.getUserNo());
        makeTagUser.setUserName(sysUser.getUserName());
        makeTagUser.setCreateTime(new Date());
        makeTagUser.setRecordId(makeTag.getRecordId());
        if (makeTag.getType() == 1){//电话
            tagService.saveTelMakeTagByUser(makeTagUser);
        } else if (makeTag.getType() == 2) {//信件
            tagService.saveMailMakeTagByUser(makeTagUser);
        }
    }
}
